import os
import time
import threading
import keyboard
import pyautogui
import pyperclip
import re

# 配置
TARGET_DIR = r"D:/Git/llz/project/at/doubao-web-auto/data/singal"
BATCH_SIZE = 15
PROGRESS_FILE = "progress.txt"

running = False
worker_thread = None

# def get_file_list():
#     """获取所有文件的完整路径"""
#     file_list = []
#     for root, dirs, files in os.walk(TARGET_DIR):
#         for file in files:
#             file_list.append(os.path.join(root, file))
#     return file_list


def get_file_list():
    """获取所有文件路径，按文件名里的数字降序排序"""
    file_list = []
    for root, dirs, files in os.walk(TARGET_DIR):
        for file in files:
            file_list.append(os.path.join(root, file))

    def extract_number(filename):
        match = re.search(r"\d+", os.path.basename(filename))
        return int(match.group()) if match else -1

    file_list.sort(key=extract_number, reverse=True)
    return file_list


def load_progress():
    if os.path.exists(PROGRESS_FILE):
        try:
            with open(PROGRESS_FILE, "r", encoding="utf-8") as f:
                return int(f.read().strip())
        except:
            return 0
    return 0


def save_progress(idx):
    with open(PROGRESS_FILE, "w", encoding="utf-8") as f:
        f.write(str(idx))


def process_files():
    global running
    try:
        files = get_file_list()
        start_index = load_progress()
        if start_index >= len(files):
            print("所有文件已处理完 ✅")
            running = False
            return

        end_index = min(start_index + BATCH_SIZE, len(files))
        print(f"本次处理 {start_index} ~ {end_index - 1}")

        for i in range(start_index, end_index):
            if not running:
                print("任务被手动停止 ⏹")
                return
            filepath = files[i]

            try:
                with open(filepath, "r", encoding="utf-8") as f:
                    content = f.read()
            except Exception as e:
                print(f"读取失败: {filepath} {e}")
                continue

            # 放入剪贴板
            pyperclip.copy(content)

            # 模拟操作
            pyautogui.hotkey("ctrl", "k")
            time.sleep(0.5)
            pyautogui.hotkey("ctrl", "v")
            time.sleep(0.5)
            pyautogui.press("enter")
            time.sleep(0.5)

            print(f"完成: {filepath}")

        save_progress(end_index)
        print(f"已保存进度: {end_index}/{len(files)}")
    except Exception as e:
        print("线程异常:", e)
    finally:
        running = False
        print("本批任务完成，等待下一次启动 ⏸")


def start_task():
    global running, worker_thread
    if running:
        print("任务已经在运行")
        return
    print("启动任务中... 🔄")
    running = True
    worker_thread = threading.Thread(target=process_files, daemon=True)
    worker_thread.start()


def stop_task():
    global running
    if not running:
        print("没有运行中的任务")
        return
    running = False
    print("任务已停止 ⏹")


def main():
    keyboard.add_hotkey("F9", start_task)
    keyboard.add_hotkey("F10", stop_task)

    print("按 F9 启动，F10 停止，F11 退出程序")
    keyboard.wait("F11")
    print("程序退出 👋")


if __name__ == "__main__":
    main()
